package com.zoe.onelink.enhancer.scanner;

import cn.hutool.core.collection.CollUtil;
import com.zoe.onelink.enhancer.init.AbstractApplicationInitializer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;

import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>标题: 类扫描器</p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2021</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2021-11-30
 */
@Slf4j
@RequiredArgsConstructor
public class ClassesScannerInvoker extends AbstractApplicationInitializer {

    private final List<ClassScanner> scanners;

    @Override
    public String eventName() {
        return "类扫描器";
    }

    @Override
    public boolean throwable() {
        return false;
    }

    @Override
    protected void doInit(ApplicationStartedEvent event) {
        if (CollUtil.isEmpty(scanners)) {
            return;
        }
        for (ClassScanner scanner : this.scanners) {
            try {
                this.invoke(scanner);
            } catch (Throwable e) {
                log.error("类扫描器异常", e);
            }
        }
    }

    private void invoke(ClassScanner scanner) {
        if (!scanner.isEnable() || CollUtil.isEmpty(scanner.baseScanPackages())) {
            return;
        }
        ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
        scanner.getIncludeTypeFilters().forEach(provider::addIncludeFilter);
        scanner.getExcludeTypeFilters().forEach(provider::addExcludeFilter);

        Set<? extends Class<?>> classes = scanner.baseScanPackages().stream()
                .flatMap(pkg -> provider.findCandidateComponents(pkg).stream())
                .map(beanDefinition -> {
                    String beanClassName = beanDefinition.getBeanClassName();
                    try {
                        return Class.forName(beanClassName);
                    } catch (Throwable e) {
                        log.debug("[类扫描器] 加载类文件[{}]失败: {} - {}", beanClassName, e.getClass().getName(), e.getMessage());
                    }
                    return null;
                }).filter(Objects::nonNull)
                .collect(Collectors.toSet());

        scanner.invoke(classes);
    }

    @Override
    public boolean isAsync() {
        return true;
    }
}
